package com.quanyan.place.service.impl;

import java.util.List;

import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.google.common.base.Strings;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.constants.CacheConstants;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.entity.TbAcResource;
import com.quanyan.place.entity.TbAdminUser;
import com.quanyan.place.entity.TbAdminUserExample;
import com.quanyan.place.entity.TbBizPlaceMember;
import com.quanyan.place.entity.TbBizPlaceMemberCard;
import com.quanyan.place.entity.TbBizPlaceMemberCardExample;
import com.quanyan.place.entity.TbCommonParameter;
import com.quanyan.place.entity.User;
import com.quanyan.place.entity.UserExample;
import com.quanyan.place.mapper.TbAdminUserMapper;
import com.quanyan.place.mapper.TbBizPlaceMemberCardMapper;
import com.quanyan.place.mapper.UserMapper;
import com.quanyan.place.service.BaseService;
import com.quanyan.place.service.PlaceMemberService;
import com.quanyan.place.service.UserService;
import com.quanyan.place.utils.PlaceUtil;

/**
 * @author songzj
 * @date 16/4/12-16:44
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TbAdminUserMapper adminUserMapper;

    @Autowired
    private PlaceRedisTemplate placeCache;
    
    @Autowired
    private BaseService baseService;
    
    @Autowired
    private PlaceMemberService placeMemberService;
    @Autowired
    private TbBizPlaceMemberCardMapper tbBizPlaceMemberCardMapper;
    
    
    private final static String PLACE_PERMISSION_SWITCH = "PLACE_PERMISSION_SWITCH";
    
    private final static Logger  logger = LoggerFactory.getLogger(UserServiceImpl.class);
    
    @Override
    public APIResponse userInfo(int id) {
        User user = this.userMapper.selectByPrimaryKey(id);
        return APIResponse.returnSuccess(user);
    }

    /**
     * H5订场用户注册
     * @param mobile
     * @return
     */
    public APIResponse userRegisterByMobileAndOpenId(String mobile,String openId){
        if (existsUser(mobile)){
            return APIResponse.returnFail("用户已存在");
        }
        User user = new User();
        user.setMobile(mobile);
        user.setNickName("用户" + mobile);
        user.setName("用户" + mobile);
        user.setGender(Constants.BYTE_ZERO);
        user.setType(Constants.BYTE_ONE);
        user.setSourceChannel(Constants.BYTE_ZERO);
        user.setIsPhoto(false);
        user.setAccount(openId);
        int result = userMapper.insertSelective(user);
        if (result > 0){
            return APIResponse.returnSuccess(user);
        } else {
            return APIResponse.returnFail("用户注册失败");
        }
    }

    @Override
    public APIResponse userRegisterByMobile(String mobile) {
        if (existsUser(mobile)){
            return APIResponse.returnFail("用户已存在");
        }
        User user = new User();
        user.setMobile(mobile);
        user.setNickName("用户" + mobile);
        user.setName("用户" + mobile);
        user.setGender(Constants.BYTE_ZERO);
        user.setType(Constants.BYTE_ONE);
        user.setSourceChannel(Constants.BYTE_ZERO);
        user.setIsPhoto(false);
        int result = userMapper.insertSelective(user);
        if (result > 0){
            return APIResponse.returnSuccess(user);
        } else {
            return APIResponse.returnFail("用户注册失败");
        }
    }

    /**
     * 通过手机号获取用户
     * @param mobile
     * @return
     */
    public User getUserByMobile(String mobile){
        User user = null;
        if (StringUtils.isEmpty(mobile)){
            return user;
        }
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andMobileEqualTo(mobile);
        List <User> userList = userMapper.selectByExample(example);
        if (null != userList && userList.size() > 0){
            user = userList.get(0);
        }
        return user;
    }

    /**
     * 判断用户是否存在
     * @param mobile
     * @return
     */
    public boolean existsUser(String mobile) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andMobileEqualTo(mobile);
        List <User> userList = userMapper.selectByExample(example);
        return null != userList && userList.size() > 0;
    }

    @Override
    public APIResponse userRegist(User user) {
        this.userMapper.insert(user);
        return APIResponse.returnSuccess(user);
    }

    @Override
    public APIResponse userLogin(String loginName, String password) {

        if (Strings.isNullOrEmpty(loginName) || Strings.isNullOrEmpty(password)) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }

        TbAdminUserExample example = new TbAdminUserExample();
        example.createCriteria().andLoginNameEqualTo(loginName).andIsDeleteEqualTo((byte)0);//未删除
        List<TbAdminUser> adminUserList = adminUserMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(adminUserList)) {
            return APIResponse.returnFail("用户不存在");
        }

        TbAdminUser tbAdminUser = adminUserList.get(0);
        String pwd = tbAdminUser.getPassword();
        //String md5Pwd = MD5Utils.MD5Encode(password);  // 前端node做了md5加密,先注释掉
        if (org.apache.commons.lang3.StringUtils.isEmpty(password)) {
            return APIResponse.returnFail("密码不能为空");
        }
        if (!pwd.equals(password)){
            return APIResponse.returnFail("密码不正确");
        }
        
        //设置场馆权限开关
     	TbCommonParameter parameter = baseService.getParameterByKey(PLACE_PERMISSION_SWITCH);
     	String permissionSwitch = parameter!=null && "on".equals(parameter.getParameterValue())? "on" : "off";
     	
     	tbAdminUser.setPermissionSwitch(permissionSwitch);
     	if ("on".equals(permissionSwitch)) {
     		 List<TbAcResource>  tbAcResourceList = adminUserMapper.getUserResource(tbAdminUser.getId());
     	     tbAdminUser.setResourceList(PlaceUtil.convertToTree(tbAcResourceList));
		}
     	
        placeCache.set(CacheConstants.PLACE_COMMON_DATA + tbAdminUser.getId().toString(), tbAdminUser);

        // 登录
       /* UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginName, md5Pwd);
        usernamePasswordToken.setRememberMe(true);
        SecurityUtils.getSubject().login(usernamePasswordToken);*/
       /* Map<String,Object> retMap = Maps.newHashMap();
        retMap.put("userInfo",tbAdminUser);*/

        return APIResponse.returnSuccess(tbAdminUser);
    }

	@Override
	public APIResponse changMobile(String mobile, Integer uid) {
		try {
			Assert.hasText(mobile, "手机号不能为空");
			Assert.notNull(uid, "用户ID不能为空");
			
			TbBizPlaceMember tbBizPlaceMember = placeMemberService.getPlaceMemberByUid(uid);
			if (tbBizPlaceMember == null) {
				return APIResponse.returnSuccess("非场馆会员");
			}
			
			TbBizPlaceMember otherTbBizPlaceMember =  placeMemberService.getPlaceMember(mobile);
			if (otherTbBizPlaceMember != null) {//将uid名下会员卡转移到新手机号上
				TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
				tbBizPlaceMemberCardExample.createCriteria().andMemberUidEqualTo(uid);
				
				TbBizPlaceMemberCard tbBizPlaceMemberCard = new TbBizPlaceMemberCard();
				tbBizPlaceMemberCard.setMemberUid(otherTbBizPlaceMember.getUid());
				tbBizPlaceMemberCardMapper.updateByExampleSelective(tbBizPlaceMemberCard, tbBizPlaceMemberCardExample);
			}
			//更新会员信息
			tbBizPlaceMember.setMobile(mobile);
			placeMemberService.updatePlaceMember(tbBizPlaceMember);
			logger.info("uid:{}, mobile:{} --> 更新手机号成功", uid, mobile);
			return APIResponse.returnSuccess();
		} catch (Exception e) {
			logger.error(String.format("uid:%s, mobile:%s --> 更新手机号失败", uid, mobile), e);
			return APIResponse.returnFail(e.getMessage());
		}
	}
}

          
